import {
  LOGIN_START,
  LOGIN_SUCCESS,
  LOGIN_FAIL
} from './actionTypes'
import {userLogin} from '../api/user'

export const loginStart = (payload)=>{ //开始登录
  return {
    type:LOGIN_START,
    payload
  }
}

export const loginSuccess = (payload,remember)=>{ //登录成功
  console.log(payload);
  return {
    type:LOGIN_SUCCESS,
    payload,
    remember
  }
}

export const loginFail = (payload)=>{ //登录失败
  return {
    type:LOGIN_FAIL,
    payload
  }
}

// 上面的三个action，需要通过登录的异步action，统一协调逻辑
export const userLoginAsync = (payload,history)=>{
  return (dispatch)=>{
    dispatch(loginStart())  //开始登录
    // 发起异步请求
    userLogin(payload).then(res=>{
      // then  登录成功
      console.log('登录成功',res);
      let {remember} = payload
      dispatch(loginSuccess(res.data,remember)) 
      history.push('/admin')
    }).catch(err=>{
      console.log('登录失败',err);
      // catch  登录失败
      dispatch(loginFail()) 
    })
  }
}